<?php

namespace app\mp\admin;

use app\common\service\Cutting as CuttingService;
use app\common\service\MaterialStockCutting as MaterialStockCuttingService;
use app\common\service\OrderMaterial as OrderMaterialService;
use app\common\service\OrderMaterialItem as OrderMaterialItemService;
use app\common\service\OrderSize as OrderSizeService;
use app\common\service\Sku as SkuService;
use app\common\service\User as UserService;
use app\system\admin\Admin;
use app\system\model\SystemUser as UserModel;
use think\Container;
use think\Db;
use think\exception\HttpResponseException;
use think\Response;

/**
 * 断码管理
 */
class BreakCode extends Admin
{

    protected $hisiModel = 'BreakCode';//模型名称[通用添加、修改专用]
    protected $hisiValidate = 'BreakCode';
    protected $hisiAddScene = '';//添加数据验证场景名
    protected $hisiEditScene = '';//更新数据验证场景名

    public function initialize()
    {
        parent::initialize();
        $break_code_size = db('break_code_size')->where([])->order("num asc, id asc")->column('name', 'id');
        $this->assign('break_code_size', $break_code_size);
        $this->assign('factoryAll', $this->_factorylist([
        ], true));
        $type = [1 => '正常', 2 => '将断码', 3 => '已断码',];
        $this->assign('type', $type);
        $this->assign('today', date('Y-m-d H:i:s'));
    }

    public function index()
    {
        if ($this->request->isAjax()) {
            $where = $data = [];
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $where = $this->_where_index($where);
            $list = db('break_code bc')
                ->field('bc.*
                ,ft.name as factory_name ,g.name as g_name
                ,GROUP_CONCAT(size.name) as size_name_all
                ')
                ->join('factory ft', "ft.id=bc.factory_id", 'left')
                ->join('wx_group g', 'g.id=bc.factory_child_id', 'left')
                ->join('break_code_detail_size bcsize', 'bcsize.break_code_id=bc.id', 'left')
                ->join('break_code_size size', 'bcsize.size_id=size.id', 'left')
                ->where($where)
                ->page($page)
                ->limit($limit)
                ->group('bc.id')
                ->order('bc.id asc')
                ->select();
            foreach ($list as $k => $v) {
                $list[$k]['type_txt'] = $this->get_txt('type', $v['type']);
                $list[$k]['is_auto_import_txt'] = $this->get_txt('is_auto_import', $v['is_auto_import']);
                $list[$k]['size_day'] = $this->get_txt('size_day', $v);
            }
            $data['count'] = db('break_code bc')
                ->join('factory ft', "ft.id=bc.factory_id", 'left')
                ->join('wx_group g', 'g.id=bc.factory_child_id', 'left')
                ->join('break_code_detail_size bcsize', 'bcsize.break_code_id=bc.id', 'left')
                ->join('break_code_size size', 'bcsize.size_id=size.id', 'left')
                ->where($where)
                ->group('bc.id')->count();
            $data['data'] = $list;
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }

        $assign = [
            'factoryKV' => [0 => '请选择'] + getFactoryKV(true),
        ];
        return $this->assign($assign)->fetch();
    }

    private function _where_index($where)
    {
        $where[] = ['bc.factory_id', '>', 0];
        $is_auto_import = $this->request->param('is_auto_import/d', 0);
        $sku = $this->request->param('sku/s', '');
        $factory_id = $this->request->param('factory_id/d', 0);
        $type = $this->request->param('type/d', 0);
        $date_range = $this->request->param('date_range/s', '');
        if ($is_auto_import > 0) {
            $where[] = ['bc.is_auto_import', '=', $is_auto_import];
        }
        if (trim($sku) != '') {
            $where[] = ['bc.sku', '=', $sku];
        }
        if ($factory_id > 0) {
            $where[] = ['bc.factory_id', '=', $factory_id];
        }
        if ($type > 0) {
            $where[] = ['bc.type', '=', $type];
        }
        if ($date_range != '') {
            list($startTime, $endTime) = array_map('strtotime', explode('~', $date_range));
            $where[] = ['bc.confirm_time', 'between', [$startTime, $endTime + 86399]];
        }
        return $where;
    }

    private function get_txt($type = '', $v)
    {
        switch ($type) {
            case 'type':
                switch ($v) {
                    case 1:
                        return '正常';
                        break;
                    case 2:
                        return '将断码';
                        break;
                    case 3:
                        return '已断码';
                        break;
                }
                break;
            case 'is_auto_import':
                return arrayGet(config('mimo.order_from'), $v);
                break;
            case 'size_day':
                if ($v['day'] > 0) {
                    switch ($v['type']) {
                        case 1:
                            return "{$v['size_name_all']}可售{$v['day']}天";
                            break;
                        case 2:
                            return "{$v['size_name_all']}可售{$v['day']}天";
                            break;
                        case 3:
                            return "{$v['size_name_all']}断码{$v['day']}天";
                            break;
                    }
                }
                return $v['size_day'];
                break;
        }
    }

    /**
     * [通用方法]添加页面展示和保存
     * @return mixed
     * @author 橘子俊 <364666827@qq.com>
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $postData = $this->request->post();
            $postData['sku'] = trim($postData['sku']);
            $postData['confirm_date'] = $postData['confirm_time'];
            $postData['confirm_time'] = strtotime($postData['confirm_time']);
            $postData['confirm_day_time'] = strtotime(date('Y-m-d', $postData['confirm_time']));
            if (!isset($postData['size'])) {
                return $this->error('请选择码信息');
            }
            $postData['size'] = implode(',', $postData['size']);
            $group_info = db('group')->where([['id', '=', $postData['factory_all']]])->find();
            $postData['factory_id'] = $group_info['factory_id'];
            $postData['factory_child_id'] = $postData['factory_all'];
            unset($postData['factory_all']);
            $postData['admin_id'] = ADMIN_ID;
            $postData['update_time'] = time();
            $postData['create_time'] = time();
            // 启动事务
            Db::startTrans();
            try {
                $id = db('break_code')->insertGetId($postData);
                $this->detail_size_action($id, $postData['size']);
                Db::commit();
                return $this->success('保存成功', '');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->error($e->getMessage());
            }
            return $this->error('失败！');
        }
        $formData = [
            'break_code_size' => '',
            'size' => '',
        ];
        $this->assign('formData', $formData);
        $template = $this->request->param('template', 'form');
        return $this->fetch($template);
    }

    /**
     *  获取所有工厂信息
     *  $this->_factorylist([
     * 'ft_id' => $info['ft_id'],
     * 'ft_type' => 1,
     * 'group_id' => $info['group_id'],
     * ]),
     * @param $param
     * @date 2021/11/27
     * @return array
     * @author zhuguosen 905502314@qq.com
     */
    private function _factorylist($param, $xm_select = false, $parent_selected = [], $child_selected = [])
    {
        $where = [];
        if (isset($param['ft_type'])) {
            $where[] = ['ft.type', '=', $param['ft_type']];
        }
        $where[] = ['ft.status', '=', 1];
        $where[] = ['g.status', '=', 1];
        $factorylist = db('factory ft')
            ->field('ft.id as ft_id,ft.name as ft_name,ft.type as ft_type 
            ,g.id as group_id,g.name as group_name ,g.factory_id as group_factory_id
            ')
            ->join('wx_group g', 'g.factory_id=ft.id', 'left')
            ->where($where)
            ->select();
        $result = [];
        foreach ($factorylist as $k => $v) {
            if (isset($result[$v['ft_id']])) {
                continue;
            }
            $result[$v['ft_id']]['ft_id'] = $v['ft_id'];
            $result[$v['ft_id']]['ft_name'] = $v['ft_name'];
            $result[$v['ft_id']]['ft_type'] = $v['ft_type'];
            $result[$v['ft_id']]['selected'] = 0;
            if (isset($param['ft_id'])) {
                $v['ft_id'] == $param['ft_id'] && $result[$v['ft_id']]['selected'] = 1;
            }
            foreach ($factorylist as $k2 => $v2) {
                if ($v2['group_factory_id'] == $v['ft_id']) {
                    $result[$v['ft_id']]['child'][$v2['group_id']]['group_id'] = $v2['group_id'];
                    $result[$v['ft_id']]['child'][$v2['group_id']]['group_name'] = $v2['group_name'];
                    $result[$v['ft_id']]['child'][$v2['group_id']]['selected'] = 0;
                    if (isset($param['group_id'])) {
                        $v2['group_id'] == $param['group_id'] && $result[$v['ft_id']]['child'][$v2['group_id']]['selected'] = 1;
                    }
                }
            }
        }
        if ($xm_select == true) {
            $factoryAll = [];
            foreach ($result as $k => $v) {
                $temp = [
                    'name' => $v['ft_name'],
                    'value' => -$v['ft_id'],
                    'children' => [],
                ];
                if (count($v['child']) > 0) {
                    foreach ($v['child'] as $k2 => $v2) {
                        $flag = false;
                        foreach ($child_selected as $ks => $vs) {
                            if ($v2['group_id'] == $vs) {
                                $flag = true;
                            }
                        }
                        $tempgrop = [
                            'name' => $v2['group_name'],
                            'value' => $v2['group_id'],
                            'selected' => $flag,
                        ];
                        $temp['children'][] = $tempgrop;
                    }
                }
                $factoryAll[] = $temp;
            }
            return $factoryAll;
        }
        return $result;
    }

    public function detail_size_action($break_code_id = 0, $size_id = '')
    {
        $list = [];
        $size_id_array = [];
        if ($size_id != '') {
            $size_id_array = explode(',', $size_id);
            foreach ($size_id_array as $k => $v) {
                $list[] = [
                    'break_code_id' => $break_code_id,
                    'size_id' => $v,
                ];
            }
        }
        //1，查询已有的信息
        $now_list = db('break_code_detail_size')->where([['break_code_id', '=', $break_code_id]])->select();
        //2，计算出 添加  删除
        $add_list = $del_list = [];
        foreach ($list as $k => $v) {
            $temp = 0;
            foreach ($now_list as $k2 => $v2) {
                if ($v2['size_id'] == $v['size_id']) {
                    $temp = 1;
                    break;
                }
            }
            if ($temp == 0) {
                $add_list[] = $v;
            }
        }
        foreach ($now_list as $k2 => $v2) {
            $temp = 0;
            foreach ($list as $k => $v) {
                if ($v2['size_id'] == $v['size_id']) {
                    $temp = 1;
                    break;
                }
            }
            if ($temp == 0) {
                $del_list[] = $v2;
            }
        }
        //3,修改表 wx_break_code_detail_size
        if (count($add_list) > 0) {
            db('break_code_detail_size')->insertAll($add_list);
        }
        if (count($del_list) > 0) {
            $where = "";
            foreach ($del_list as $k => $v) {
                $where .= "(break_code_id={$v['break_code_id']} and size_id={$v['size_id']}) or ";
            }
            $where = substr($where, 0, -3);
            db('break_code_detail_size')->where($where)->delete();
        }
    }

    public function edit()
    {
        $id = $this->request->param('id/d', 0);
        if ($this->request->isPost()) {
            $postData = $this->request->post();
            $postData['sku'] = trim($postData['sku']);
            $postData['confirm_date'] = $postData['confirm_time'];
            $postData['confirm_time'] = strtotime($postData['confirm_time']);
            $postData['confirm_day_time'] = strtotime(date('Y-m-d', $postData['confirm_time']));
            if (!isset($postData['size'])) {
                return $this->error('请选择码信息');
            }
            $postData['size'] = implode(',', $postData['size']);
            $group_info = db('group')->where([['id', '=', $postData['factory_all']]])->find();
            $postData['factory_id'] = $group_info['factory_id'];
            $postData['factory_child_id'] = $postData['factory_all'];
            unset($postData['factory_all']);
            $postData['admin_id'] = ADMIN_ID;
            $postData['update_time'] = time();
            $postData['create_time'] = time();
            // 启动事务
            Db::startTrans();
            try {
                db('break_code')->where([['id', '=', $postData['id']]])->update($postData);
                $this->detail_size_action($postData['id'], $postData['size']);
                Db::commit();
                return $this->success('保存成功', '');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->error($e->getMessage());
            }
            return $this->error('失败！');
        }
        $formData = db('break_code')->where([['id', '=', $id]])->find();
        $this->assign('formData', $formData);
        $this->assign('today', $formData['confirm_date']);
        $this->assign('factoryAll', $this->_factorylist([
        ], true, [], [$formData['factory_child_id']]));
        $template = $this->request->param('template', 'form');
        return $this->fetch($template);
    }

    public function del()
    {
        $id = $this->request->param('id/a');
        // 启动事务
        Db::startTrans();
        try {
            db('break_code')->where([['id', 'in', $id]])->delete();
            foreach ($id as $k => $v) {
                $this->detail_size_action($v, '');
            }
            Db::commit();
            return $this->success('删除成功', '');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->error($e->getMessage());
        }
        return $this->error('删除失败！');
    }

    /**
     * 导入xls
     *  date 2022年02月24日
     * @param file $_File
     * @param array bool
     */
    public function import()
    {
        set_time_limit(60 * 5);
        ini_set('memory_limit', '512M');
        error_reporting(E_ALL & ~E_NOTICE);
        if (isset($_FILES)) {
            $params = $paramsSz = $paramsOm = $paramsMl = [];
            $params['file_path'] = $_FILES['file']['tmp_name'];
            // 数据开始行（非必须，正常第一行为表头，所以默认值为2）
            $params['start'] = 1;
            // 模型（表名或模型二选一）
            $params['model'] = 'cms/content';
            $resultAll = plugins_run('excel/excel/import', $params);
            if ($resultAll === false) {
                return $this->error('excel读取失败');
            }
            foreach ($resultAll as $keyr => $valuer) {
                foreach ($valuer as $k2 => $v2) {
                    //PHP 清除 Excel 导入的数据空格 https://www.cnblogs.com/xtmp/p/10773662.html
                    $resultAll[$keyr][$k2] = preg_replace("/(\s|\&nbsp\;|　|\xc2\xa0)/", "", $v2);
                }
            }
            //检测
            $result_head = array_shift($resultAll);
            $result = [];
            $read_i = 0;
            foreach ($resultAll as $keyr => $valuer) {
                if (trim($valuer['A']) == '' && $read_i > 10) {
                    break;
                }
                if (trim($valuer['A']) == '') {
                    $read_i++;
                    continue;
                }
                $vnewr = [];
                $vnewr['sku'] = $valuer['A'];
                $vnewr['type_txt'] = $valuer['B'];
                $vnewr['is_auto_import_txt'] = $valuer['C'];
                $vnewr['average_daily_sales_num'] = $valuer['D'];
                $vnewr['size_day'] = $valuer['E'];
                $vnewr['factory_name'] = $valuer['F'];
                $vnewr['factory_child_name'] = $valuer['G'];
                $vnewr['confirm_date'] = $valuer['H'];
                //格式过滤--特别是时间
                if (strtotime($vnewr['confirm_date']) < 100000000) {
                    return $this->error('excel的时间读取失败', null, $vnewr);
                }
                $result[] = $vnewr;
            }
            //10,检验数据格式与处理
            $result = $this->_import_data_deal_with($result);
            if ($result['code'] > 1) {
                return $this->Json(0, $result['msg'], $result);
            }
            //11,合法就插入
            try {
                db()->startTrans();
                $count = db('break_code')->insertAll($result['data']);
                if ($count != count($result['data'])) {
                    db()->rollback();
                    return $this->Json(0, "导入失败，", $count);
                }
                db()->commit();
                return $this->Json(1, "导入成功");
            } catch (\Exception $e) {
                db()->rollback();
                return $this->Json(0, "导入失败，" . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
            }
            // 导入成功将自动返回新增ID，请自行打印$result查看
        }
    }

    private function _import_data_deal_with($result)
    {
        //随机插入数据
//        foreach ($result as $k => $v) {
//            $result[$k]['confirm_date'] = date('Y-m-d', 1577808000 + 3600 * 24 * rand(0, (365 + 60)));
//            $result[$k]['sku'] = "sku" . ($k + 1033);
//        }
        foreach ($result as $k => $v) {
            $result[$k]['type'] = $this->get_txt_id('type', $v['type_txt']);
            if ($result[$k]['type'] == 0) {
                return ['code' => 10, 'msg' => "sku为{$v['sku']}的分类，不存在", 'data' => $v];
            }
            $result[$k]['is_auto_import'] = $this->get_txt_id('is_auto_import', $v['is_auto_import_txt']);
            if ($result[$k]['is_auto_import'] == 0) {
                return ['code' => 11, 'msg' => "sku为{$v['sku']}的来源帐号，不存在", 'data' => $v];
            }
            //工厂处理
            $factory_info = $this->get_txt_id('factory', $v);
            if ($factory_info == []) {
                return ['code' => 12, 'msg' => "sku为{$v['sku']}的工厂名，不存在", 'data' => $v];
            }
            $result[$k]['factory_id'] = $factory_info['factory_id'];
            $result[$k]['factory_child_id'] = $factory_info['factory_child_id'];
            $result[$k]['confirm_time'] = strtotime("{$v['confirm_date']} 00:00:00");
            $result[$k]['confirm_day_time'] = strtotime("{$v['confirm_date']} 00:00:00");
            $result[$k]['admin_id'] = ADMIN_ID;
            $result[$k]['update_time'] = time();
            $result[$k]['create_time'] = time();
            unset($result[$k]['type_txt']);
            unset($result[$k]['is_auto_import_txt']);
            unset($result[$k]['factory_name']);
            unset($result[$k]['factory_child_name']);
        }
        return ['code' => 0, 'msg' => "", 'data' => $result];;
    }

    private function get_txt_id($type = '', $v)
    {
        switch ($type) {
            case 'type':
                switch ($v) {
                    case  '正常':
                        return 1;
                        break;
                    case '将断码':
                        return 2;
                        break;
                    case '已断码':
                        return 3;
                        break;
                }
                return 0;
                break;
            case 'is_auto_import':
                foreach (config('mimo.order_from') as $k2 => $v2) {
                    if ($v2 == $v) {
                        return $k2;
                    }
                }
                return 0;
                break;
            case 'size_day':
                if ($v['day'] > 0) {
                    switch ($v['type']) {
                        case 1:
                            return "{$v['size_name_all']}可售{$v['day']}天";
                            break;
                        case 2:
                            return "{$v['size_name_all']}可售{$v['day']}天";
                            break;
                        case 3:
                            return "{$v['size_name_all']}断码{$v['day']}天";
                            break;
                    }
                }
                return $v['size_day'];
                break;
            case 'factory':
                $p_info = db('factory')->where([['name', '=', $v['factory_name']]])->find();
                $c_info = db('group')->where([['name', '=', $v['factory_child_name']]])->find();
                if ($p_info == null && $c_info == null) {
                    return [];
                }
                if ($c_info == null) {
                    return ['factory_id' => $p_info['id'], 'factory_child_id' => 0,];
                }
                if ($p_info == null) {
                    return ['factory_id' => $c_info['factory_id'], 'factory_child_id' => $c_info['id'],];
                }
                if ($p_info['id'] != $c_info['factory_id']) {
                    return ['factory_id' => $p_info['id'], 'factory_child_id' => 0,];
                }
                return ['factory_id' => $c_info['factory_id'], 'factory_child_id' => $c_info['id'],];
                break;
        }
        return 0;
    }

    /**
     * 断码率--统计报表
     */
    public function statistics()
    {
        //主题处理
        $themes = $this->request->param('themes', '');
        $themes = $this->_set_get_themes($themes);
        if ($this->request->isAjax()) {
            //获取参数，并处理
            $param = $this->_statistics_getParam();
            $param['type_name'] = '断码率';
            //查询数据
            $data = $this->_statistics_searchData($param);
            //处理数据 以适应图表
            $highcharts_data = $this->_statistics_dealWith($param, $data);
            return json(['code' => 0, 'msg' => '', 'data' => $highcharts_data]);
        }
        $assign = [
            'searchdate' => [
                '', date("Y-m-d", time() - 6 * 24 * 3600), date("Y-m-d"), date("Y-m-d", time() - 30 * 24 * 3600), date("Y-m-d"),
                date("Y-m-01", strtotime('-3 month')), date("Y-m-d"),
                date("Y-m-01", strtotime('-6 month')), date("Y-m-d")
            ],
            'factoryKV' => [0 => '请选择'] + getFactoryKV(true),
            'create_date_range' => date("Y-m-d", time() - 7 * 24 * 3600) . ' ~ ' . date('Y-m-d'),
            'themes' => $this->_get_hightchart_themes(),
            'this_themes' => $themes,
            'this_themes_url' => $themes == 'not_load' ? '' : get_domain() . "/static/js/Highcharts@9.3.2/code/themes/{$themes}",
        ];
        return $this->assign($assign)->fetch();
    }

    /**
     * 记忆操作--用户选择的主题设置
     * @author zhuguosen 905502314@qq.com
     * @date 2022/3/15
     */
    private function _set_get_themes($themes)
    {
        $info = db('break_code_themes')->where([
            ['admin_id', '=', ADMIN_ID],
        ])->find();
        if ($themes == '' && isset($info['themes'])) {
            return $info['themes'];
        }
        $themes == '' && $themes = 'not_load';
        if (isset($info['id'])) {
            db('break_code_themes')->where([
                ['admin_id', '=', ADMIN_ID],
            ])->update(['themes' => $themes]);
        } else {
            db('break_code_themes')->insert([
                'admin_id' => ADMIN_ID,
                'themes' => $themes,
            ]);
        }
        return $themes;
    }

    private function _get_hightchart_themes()
    {
        $themes = [
            'not_load' => '无主题',
            'dark-unica.js' => 'dark-unica',
            'sand-signika.js' => 'sand-signika',
            'grid-light.js' => 'grid-light',
        ];
        $dir = env('root_path') . "public/static/js/Highcharts@9.3.2/code/themes/";
        $file = scandir($dir);
        foreach ($file as $k => $v) {
            if ($v != '.' && $v != '..') {
                $temp = explode('.', $v);
                $you = 0;
                foreach ($themes as $k2 => $v2) {
                    if ($temp[0] == $v2) {
                        $you = 1;
                        break;
                    }
                }
                $you == 0 && $themes[$v] = $temp[0];
            }
        }
        return $themes;
    }

    private function _statistics_getParam()
    {
        $param = [
            'unit' => $this->request->param('unit', 'month'),
            'create_date_range' => $this->request->param('create_date_range', ''),
        ];
        list($param['start_time'], $param['end_time']) = array_map('strtotime', explode('~', $param['create_date_range']));
        list($param['start'], $param['end']) = array_map('trim', explode('~', $param['create_date_range']));
        $param['end_time'] += 24 * 3600 - 1;
        return $param;
    }

    private function _statistics_searchData($param)
    {
        $sql_factory = 'bc.factory_id>0';
        if (FACTORY_IDS != '*') {
            $temp = implode(',', FACTORY_IDS);
            $sql_factory = " bc.factory_id in ({$temp} ) ";
        }
        $result = [];
        switch ($param['unit']) {
            case 'month':
                //断码  小辉辉
                $sql = "SELECT   date_format(bc.confirm_date,'%y-%m') as sdate ,bc.factory_id ,f.name as factory_name
,ROUND( sum(if(bc.type=3,1,0)) / count(bc.id) * 100, 2) as num
FROM wx_break_code bc
LEFT JOIN wx_factory f ON (bc.factory_id=f.id)
where  bc.is_auto_import=1  and {$sql_factory}
and bc.confirm_time >= {$param['start_time']} and bc.confirm_time <={$param['end_time']}
group by  sdate,bc.factory_id
order by bc.confirm_time asc
";
                $xiaohuihui_3 = db()->query($sql);
                $xiaohuihui_3 = $this->_date_bu($param, $xiaohuihui_3, 'month_0');
                //断码  名贵坊
                $sql = "SELECT   date_format(bc.confirm_date,'%y-%m') as sdate ,bc.factory_id ,f.name as factory_name
,ROUND( sum(if(bc.type=3,1,0)) / count(bc.id) * 100, 2) as num
FROM wx_break_code bc
LEFT JOIN wx_factory f ON (bc.factory_id=f.id)
where  bc.is_auto_import=2  and {$sql_factory}
and bc.confirm_time >= {$param['start_time']} and bc.confirm_time <={$param['end_time']}
group by  sdate,bc.factory_id
order by bc.confirm_time asc
";
                $minguifang_3 = db()->query($sql);
                $minguifang_3 = $this->_date_bu($param, $minguifang_3, 'month_0');
                //断码  汇总
                $sql = "SELECT   date_format(bc.confirm_date,'%y-%m') as sdate ,bc.factory_id ,f.name as factory_name
,ROUND( sum(if(bc.type=3,1,0)) / count(bc.id) * 100, 2) as num
FROM wx_break_code bc
LEFT JOIN wx_factory f ON (bc.factory_id=f.id)
where  {$sql_factory}
and bc.confirm_time >= {$param['start_time']} and bc.confirm_time <={$param['end_time']}
group by  sdate,bc.factory_id
order by bc.confirm_time asc
";
                $all_3 = db()->query($sql);
                $all_3 = $this->_date_bu($param, $all_3, 'month_0');
                return [
                    'xiaohuihui_3' => $xiaohuihui_3,
                    'minguifang_3' => $minguifang_3,
                    'all_3' => $all_3,
                ];
                break;
            case 'week':
                //断码  小辉辉
                $sql = "SELECT    DATE_FORMAT( bc.confirm_date, '%Y-%u' ) AS week
,DATE_FORMAT(date_sub( bc.confirm_date, INTERVAL dayofweek( bc.confirm_date )- 2 DAY ),'%Y-%m-%d') AS sdate
,date_format(bc.confirm_date,'%y-%u') as sdate2 
,bc.factory_id ,f.name as factory_name
,ROUND( sum(if(bc.type=3,1,0)) / count(bc.id) * 100, 2) as num
FROM wx_break_code bc
LEFT JOIN wx_factory f ON (bc.factory_id=f.id)
where  bc.is_auto_import=1 and {$sql_factory}
and bc.confirm_time >= {$param['start_time']} and bc.confirm_time <={$param['end_time']}
group by  sdate2,bc.factory_id
order by bc.confirm_time asc
";
                $xiaohuihui_3 = db()->query($sql);
                $xiaohuihui_3 = $this->_date_bu($param, $xiaohuihui_3, 'week_0');
                //断码  名贵坊
                $sql = "SELECT   DATE_FORMAT( bc.confirm_date, '%Y-%u' ) AS week
,DATE_FORMAT(date_sub( bc.confirm_date, INTERVAL dayofweek( bc.confirm_date )- 2 DAY ),'%Y-%m-%d') AS sdate
,date_format(bc.confirm_date,'%y-%u') as sdate2 
,bc.factory_id ,f.name as factory_name
,ROUND( sum(if(bc.type=3,1,0)) / count(bc.id) * 100, 2) as num
FROM wx_break_code bc
LEFT JOIN wx_factory f ON (bc.factory_id=f.id)
where  bc.is_auto_import=2  and {$sql_factory}
and bc.confirm_time >= {$param['start_time']} and bc.confirm_time <={$param['end_time']}
group by  sdate2,bc.factory_id
order by bc.confirm_time asc
";
                $minguifang_3 = db()->query($sql);
                $minguifang_3 = $this->_date_bu($param, $minguifang_3, 'week_0');
                //断码  汇总
                $sql = "SELECT   DATE_FORMAT( bc.confirm_date, '%Y-%u' ) AS week
,DATE_FORMAT(date_sub( bc.confirm_date, INTERVAL dayofweek( bc.confirm_date )- 2 DAY ),'%Y-%m-%d') AS sdate
,date_format(bc.confirm_date,'%y-%u') as sdate2 
,bc.factory_id ,f.name as factory_name
,ROUND( sum(if(bc.type=3,1,0)) / count(bc.id) * 100, 2) as num
FROM wx_break_code bc
LEFT JOIN wx_factory f ON (bc.factory_id=f.id)
where  {$sql_factory}
and bc.confirm_time >= {$param['start_time']} and bc.confirm_time <={$param['end_time']}
group by  sdate2,bc.factory_id
order by bc.confirm_time asc
";
                $all_3 = db()->query($sql);
                $all_3 = $this->_date_bu($param, $all_3, 'week_0');
                return [
                    'xiaohuihui_3' => $xiaohuihui_3,
                    'minguifang_3' => $minguifang_3,
                    'all_3' => $all_3,
                ];
                break;
            case 'day':
                //断码  小辉辉
                $sql = "SELECT   date_format(bc.confirm_date,'%y-%m-%d') as sdate ,bc.factory_id ,f.name as factory_name
,ROUND( sum(if(bc.type=3,1,0)) / count(bc.id) * 100, 2) as num
FROM wx_break_code bc
LEFT JOIN wx_factory f ON (bc.factory_id=f.id)
where  bc.is_auto_import=1  and {$sql_factory}
and bc.confirm_time >= {$param['start_time']} and bc.confirm_time <={$param['end_time']}
group by  sdate,bc.factory_id
order by bc.confirm_time asc
";
                $xiaohuihui_3 = db()->query($sql);
                $xiaohuihui_3 = $this->_date_bu($param, $xiaohuihui_3, 'day_0');
                //断码  名贵坊
                $sql = "SELECT   date_format(bc.confirm_date,'%y-%m-%d') as sdate ,bc.factory_id ,f.name as factory_name
,ROUND( sum(if(bc.type=3,1,0)) / count(bc.id) * 100, 2) as num
FROM wx_break_code bc
LEFT JOIN wx_factory f ON (bc.factory_id=f.id)
where  bc.is_auto_import=2  and {$sql_factory}
and bc.confirm_time >= {$param['start_time']} and bc.confirm_time <={$param['end_time']}
group by  sdate,bc.factory_id
order by bc.confirm_time asc
";
                $minguifang_3 = db()->query($sql);
                $minguifang_3 = $this->_date_bu($param, $minguifang_3, 'day_0');
                //断码   汇总
                $sql = "SELECT   date_format(bc.confirm_date,'%y-%m-%d') as sdate ,bc.factory_id ,f.name as factory_name
,ROUND( sum(if(bc.type=3,1,0)) / count(bc.id) * 100, 2) as num
FROM wx_break_code bc
LEFT JOIN wx_factory f ON (bc.factory_id=f.id)
where  {$sql_factory}
and bc.confirm_time >= {$param['start_time']} and bc.confirm_time <={$param['end_time']}
group by  sdate,bc.factory_id
order by bc.confirm_time asc
";
                $all_3 = db()->query($sql);
                $all_3 = $this->_date_bu($param, $all_3, 'day_0');
                return [
                    'xiaohuihui_3' => $xiaohuihui_3,
                    'minguifang_3' => $minguifang_3,
                    'all_3' => $all_3,
                ];
                break;
        }
        return $result;
    }

    /**
     * 日期补充
     * 以下是填表
     * //        $date = '2021-01-01';
     * //        $time = strtotime("$date 00:00:00");
     * //        $insert_data = [];
     * //        for ($d = 0; $d <= 365 * 20; $d++) {
     * //            $temp = [
     * //                'time' => $time + $d * 24 * 3600,
     * //                'date' => date('Y-m-d H:i:s', $time + $d * 24 * 3600),
     * //            ];
     * //            $insert_data[] = $temp;
     * //            if ($d > 0 && $d % 10 == 0) {
     * //                db('break_code_date')->insertAll($insert_data);
     * //                $insert_data = [];
     * //            }
     * //        }
     * @param $param
     * @param $xiaohuihui_3
     * @param string $type
     */
    private function _date_bu($param, $data, $type = 'week_0')
    {
        switch ($type) {
            case 'week_0':
                $sql = "SELECT    DATE_FORMAT( date, '%Y-%u' ) AS week
,DATE_FORMAT(date_sub( date, INTERVAL dayofweek( date )- 2 DAY ),'%Y-%m-%d') AS sdate
,date_format(date,'%y-%u') as sdate2 
FROM wx_break_code_date 
where time >= {$param['start_time']} and time <={$param['end_time']}
order by id asc
";
                $date_array = db()->query($sql);
                $factory_id_all = [];
                foreach ($data as $k => $v) {
                    $factory_id_all[$v['factory_id']] = $v['factory_name'];
                }
                $res = [];
                foreach ($date_array as $k => $v) {
                    foreach ($factory_id_all as $k2 => $v2) {
                        $temp = [//group by  sdate2,bc.factory_id
                            'week' => $v['week'],
                            'sdate' => $v['sdate'],
                            'sdate2' => $v['sdate2'],
                            'factory_id' => $k2,
                            'factory_name' => $v2,
                            'num' => 0,
                        ];
                        foreach ($data as $k3 => $v3) {
                            if ($v3['sdate'] == $v['sdate'] && $v3['factory_id'] == $k2) {
                                $temp['num'] = $v3['num'];
                                break;
                            }
                        }
                        $res[] = $temp;
                    }
                }
                return $res;
                break;
            case 'month_0':
                $sql = "SELECT  date_format(date,'%y-%m') as sdate 
FROM wx_break_code_date 
where time >= {$param['start_time']} and time <={$param['end_time']}
order by id asc
";
                $date_array = db()->query($sql);
                $factory_id_all = [];
                foreach ($data as $k => $v) {
                    $factory_id_all[$v['factory_id']] = $v['factory_name'];
                }
                $res = [];
                foreach ($date_array as $k => $v) {
                    foreach ($factory_id_all as $k2 => $v2) {
                        $temp = [//group by  sdate2,bc.factory_id
                            'sdate' => $v['sdate'],
                            'factory_id' => $k2,
                            'factory_name' => $v2,
                            'num' => 0,
                        ];
                        foreach ($data as $k3 => $v3) {
                            if ($v3['sdate'] == $v['sdate'] && $v3['factory_id'] == $k2) {
                                $temp['num'] = $v3['num'];
                                break;
                            }
                        }
                        $res[] = $temp;
                    }
                }
                return $res;
                break;
            case 'day_0':
                $sql = "SELECT  date_format(date,'%y-%m-%d') as sdate 
FROM wx_break_code_date 
where time >= {$param['start_time']} and time <={$param['end_time']}
order by id asc
";
                $date_array = db()->query($sql);
                $factory_id_all = [];
                foreach ($data as $k => $v) {
                    $factory_id_all[$v['factory_id']] = $v['factory_name'];
                }
                $res = [];
                foreach ($date_array as $k => $v) {
                    foreach ($factory_id_all as $k2 => $v2) {
                        $temp = [//group by  sdate2,bc.factory_id
                            'sdate' => $v['sdate'],
                            'factory_id' => $k2,
                            'factory_name' => $v2,
                            'num' => 0,
                        ];
                        foreach ($data as $k3 => $v3) {
                            if ($v3['sdate'] == $v['sdate'] && $v3['factory_id'] == $k2) {
                                $temp['num'] = $v3['num'];
                                break;
                            }
                        }
                        $res[] = $temp;
                    }
                }
                return $res;
                break;
        }
    }

    private function _statistics_dealWith($param = [], $data = [])
    {
        $xiaohuihui_3 = $minguifang_3 = $all_3 = [
//            'chart' => [
//                'type' => 'line',
//            ],
            'title' => [
                'text' => '月平均气温23',
            ],
            'subtitle' => [
                'text' => '数据来源: WorldClimate.com',
            ],
            'xAxis' => [
                'categories' => ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
                //标示线
//                'plotLines' => [[
//                    'color' => 'red',            //线的颜色，定义为红色
//                    'dashStyle' => 'longdashdot',//标示线的样式，默认是solid（实线），这里定义为长虚线
//                    'value' => 3,                //定义在哪个值上显示标示线，这里是在x轴上刻度为3的值处垂直化一条线
//                    'width' => 2                 //标示线的宽度，2px
//                ]],
            ],
            'yAxis' => [
                'title' => [
                    'text' => ''
                ],
            ],
            'plotOptions' => [
                'series' => [
                    'label' => [
                        'connectorAllowed' => false
                    ],
//                    'pointStart' => 2010,
                ],
                'line' => [
                    'dataLabels' => [
                        'enabled' => true,// 开启数据标签
                    ],
//                    'enableMouseTracking' => false, // 关闭鼠标跟踪，对应的提示框、点击事件会失效
                ],
            ],
            'series' => [
                [
                    'name' => '东京',
                    'data' => [7.0, 6.9, 9.5, 14.5, 18.4, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6],
                ],
                [
                    'name' => '伦敦',
                    'data' => [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8],
                ],
            ],
            'credits' => [
                'enabled' => false,//版权信息 关闭
            ],
            'legend' => [
                'layout' => 'vertical',
                'align' => 'left',
                'verticalAlign' => 'middle',
            ],
            'tooltip' => [
                'pointFormatter' => "",
            ]
        ];
        $xiaohuihui_3['title']['text'] = "{$param['type_name']}：小辉辉";
        $minguifang_3['title']['text'] = "{$param['type_name']}：名贵坊";
        $all_3['title']['text'] = "{$param['type_name']}：汇总";
        $xiaohuihui_3['subtitle']['text'] = "";
        $minguifang_3['subtitle']['text'] = "";
        $all_3['subtitle']['text'] = "";
        $xiaohuihui_3['xAxis']['categories'] = $this->_get_xAxis_categories($data['xiaohuihui_3']);
        $minguifang_3['xAxis']['categories'] = $this->_get_xAxis_categories($data['minguifang_3']);
        $all_3['xAxis']['categories'] = $this->_get_xAxis_categories($data['all_3']);
        $xiaohuihui_3['series'] = $this->_get_series($data['xiaohuihui_3'], $xiaohuihui_3['xAxis']['categories']);
        $minguifang_3['series'] = $this->_get_series($data['minguifang_3'], $minguifang_3['xAxis']['categories']);
        $all_3['series'] = $this->_get_series($data['all_3'], $all_3['xAxis']['categories']);
        return [
            'xiaohuihui_3' => $xiaohuihui_3,
            'minguifang_3' => $minguifang_3,
            'all_3' => $all_3,
        ];
    }

    private function _get_xAxis_categories($data)
    {
        $xAxis_categories = [];
        foreach ($data as $k => $v) {
            $xAxis_categories[$v['sdate']] = 0;
        }
        $xAxis_categories_res = [];
        foreach ($xAxis_categories as $k => $v) {
            $xAxis_categories_res[] = $k;
        }
        return $xAxis_categories_res;
    }

    private function _get_series($data, $categories)
    {
        $res = [];
        $f_list = [];
        foreach ($data as $k => $v) {
            if ($v['factory_id'] == -2) {
                $v['factory_name'] = '';
            }
            $f_list[$v['factory_name']][] = [
                'sdate' => $v['sdate'],
                'num' => $v['num'],
            ];
        }
        foreach ($f_list as $k => $v) {
            $temp = [
                'name' => $k,
                'data' => [],
            ];
            foreach ($categories as $k2 => $v2) {
                $flag = 0;
                $num = 0;
                foreach ($v as $k3 => $v3) {
                    if ($v2 == $v3['sdate']) {
                        $num = $v3['num'];
                        $flag = 1;
                        break;
                    }
                }
                $temp['data'][] = floatval($num);//必须是数值，不能字符串
            }
            $res[] = $temp;
        }
        //平均值获取
        $avg = [
            'name' => '平均值',
            'data' => [],
        ];
        $c = count($res);
        $temp_sum = [];
        foreach ($res as $k => $v) {
            foreach ($v['data'] as $k2 => $v2) {
                $temp_sum[$k2] ?? $temp_sum[$k2] = 0;
                $temp_sum[$k2] += $v2;
            }
        }
        foreach ($temp_sum as $k => $v) {
            $avg['data'][] = floatval(sprintf("%.2f", $v / $c));
        }
        $res[] = $avg;
        return $res;
    }

    /**
     * 汇总分析
     */
    public function metaAnalysis()
    {
        if ($this->request->isAjax()) {
            $where = $data = [];
            $page = $this->request->param('page/d', 1);
            $limit = $this->request->param('limit/d', 20);
            $where = $this->_where_metaAnalysis($where);
            $list = db('break_code bc')
                ->field(" bc.id, date_format(bc.confirm_date,'%Y-%m-%d') as sdate ,bc.is_auto_import ,bc.factory_id ,ft.name as factory_name 
,sum(bc.average_daily_sales_num) as num
,sum( if(bc.type=1,bc.average_daily_sales_num,0)) as num_1
,sum( if(bc.type=2,bc.average_daily_sales_num,0)) as num_2
,sum( if(bc.type=3,bc.average_daily_sales_num,0)) as num_3
                ")
                ->join('factory ft', "ft.id=bc.factory_id", 'left')
                ->where($where)
                ->page($page)
                ->limit($limit)
                ->group(' sdate ,bc.is_auto_import ,bc.factory_id')
                ->order(' bc.confirm_time desc,bc.is_auto_import asc')
                ->select();
            $data['count'] = db('break_code bc')
                ->field("  date_format(bc.confirm_date,'%y-%m-%d') as sdate ")
                ->join('factory ft', "ft.id=bc.factory_id", 'left')
                ->where($where)
                ->group(' sdate ,bc.is_auto_import ,bc.factory_id')
                ->count();
            $meta_list = [];//汇总
            foreach ($list as $k => $v) {
                $meta_list[$v['sdate']][$v['is_auto_import']][$v['factory_id']]['num'] ?? $meta_list[$v['sdate']][$v['is_auto_import']][$v['factory_id']]['num'] = 0;
                $meta_list[$v['sdate']][$v['is_auto_import']][$v['factory_id']]['num'] += $v['num'];
                $meta_list[$v['sdate']][$v['is_auto_import']][$v['factory_id']]['num_1'] ?? $meta_list[$v['sdate']][$v['is_auto_import']][$v['factory_id']]['num_1'] = 0;
                $meta_list[$v['sdate']][$v['is_auto_import']][$v['factory_id']]['num_1'] += $v['num_1'];
                $meta_list[$v['sdate']][$v['is_auto_import']][$v['factory_id']]['num_2'] ?? $meta_list[$v['sdate']][$v['is_auto_import']][$v['factory_id']]['num_2'] = 0;
                $meta_list[$v['sdate']][$v['is_auto_import']][$v['factory_id']]['num_2'] += $v['num_2'];
                $meta_list[$v['sdate']][$v['is_auto_import']][$v['factory_id']]['num_3'] ?? $meta_list[$v['sdate']][$v['is_auto_import']][$v['factory_id']]['num_3'] = 0;
                $meta_list[$v['sdate']][$v['is_auto_import']][$v['factory_id']]['num_3'] += $v['num_3'];
            }
            $res_list = [];
            $pre_value = [];
            $meta_i = 0;
            $list[] = [//最后特别数据。方便后面计算
                'sdate' => 'end',
                'is_auto_import' => -1,
            ];
            foreach ($list as $k => $v) {
                //插入小总汇
                $this->_metaAnalysis_min_list($res_list, $pre_value, $v, $meta_i, $meta_list);
                //插入大总汇
//                $this->_metaAnalysis_max_list($res_list, $pre_value, $v, $meta_i, $meta_list, $list);
                $v['ext_data'] = [
                    'type' => 'day',
                    'sdate' => $v['sdate'],
                    'is_auto_import' => $v['is_auto_import'],
                ];
                isset($v['id']) && $res_list[] = $v;
                $pre_value = $v;
            }
            foreach ($res_list as $k => $v) {
                $res_list[$k]['is_auto_import_txt'] = $v['is_auto_import'] == 100 ? '汇总' : $this->get_txt('is_auto_import', $v['is_auto_import']);
                $res_list[$k]['num_1_num_3'] = sprintf('%.2f', ($v['num'] <= 0 ? 0 : $v['num_3'] / $v['num']) * 100);
                $res_list[$k]['num_1_num_3_end'] = sprintf('%.2f', 0);
                //样式处理
                $res_list[$k]['factory_name_html'] = $v['factory_name_html'] ?? $v['factory_name'];
                $res_list[$k]['num_html'] = $v['num_html'] ?? $v['num'];
                $res_list[$k]['num_1_html'] = $v['num_1_html'] ?? $v['num_1'];
                $res_list[$k]['num_2_html'] = $v['num_2_html'] ?? $v['num_2'];
                $res_list[$k]['num_3_html'] = $v['num_3_html'] ?? $v['num_3'];
                $res_list[$k]['num_1_num_3_html'] = isset($v['factory_name_html']) ? "<span class='bold'>{$res_list[$k]['num_1_num_3']}</span>" : $res_list[$k]['num_1_num_3'];
            }
            $res_list = $this->_metaAnalysis_num_1_num_3_end($res_list);
            $data['data'] = $res_list;
            $data['code'] = 0;
            $data['msg'] = '';
            $data['meta_list'] = $meta_list;
            return json($data);
        }
        $assign = [
            'factoryKV' => [0 => '请选择'] + getFactoryKV(true),
        ];
        return $this->assign($assign)->fetch();
    }

    private function _metaAnalysis_min_list(&$res_list, $pre_value, $v, &$meta_i, $meta_list)
    {
        if ($pre_value != []
            && ($pre_value['sdate'] != $v['sdate'] || $pre_value['is_auto_import'] != $v['is_auto_import'])
        ) {
            $meta_i--;
            $temp = [
                'id' => $meta_i,
                'sdate' => '',
                'is_auto_import' => '',
                'factory_id' => 0,
                'factory_name' => "汇总",
                'num' => 0,
                'num_1' => 0,
                'num_2' => 0,
                'num_3' => 0,
                'ext_data' => [
                    'type' => 'min_meta',
                    'sdate' => $pre_value['sdate'],
                    'is_auto_import' => $pre_value['is_auto_import'],
                ],
            ];
            foreach ($meta_list[$pre_value['sdate']][$pre_value['is_auto_import']] as $k2 => $v2) {
                $temp['num'] += $v2['num'];
                $temp['num_1'] += $v2['num_1'];
                $temp['num_2'] += $v2['num_2'];
                $temp['num_3'] += $v2['num_3'];
            }
            $temp = $this->_add_metaAnalysis_bold($temp);
            $res_list[] = $temp;
            $insert_flag['_metaAnalysis_min_list'] = 1;
        }
    }

    private function _metaAnalysis_max_list(&$res_list, $pre_value, $v, &$meta_i, $meta_list, $list)
    {
        if ($pre_value != [] && $pre_value['sdate'] != $v['sdate']
            && count($meta_list[$pre_value['sdate']]) >= 2 //同一天 来源帐号有2个以上，才显示
        ) {
            $f_temp = [];
            foreach ($meta_list[$pre_value['sdate']] as $k2 => $v2) {
                foreach ($v2 as $k3 => $v3) {
                    $meta_i--;
                    !isset($f_temp[$k3]) && $f_temp[$k3] = [
                        'id' => $meta_i,
                        'sdate' => $pre_value['sdate'],
                        'is_auto_import' => 100,
                        'factory_id' => $k3,
                        'factory_name' => '工厂名',
                        'num' => 0,
                        'num_1' => 0,
                        'num_2' => 0,
                        'num_3' => 0,
                        'ext_data' => [
                            'type' => 'max_meta_min',
                            'sdate' => $pre_value['sdate'],
                            'is_auto_import' => 100,
                        ],
                    ];
                    $f_temp[$k3]['num'] += $v3['num'];
                    $f_temp[$k3]['num_1'] += $v3['num_1'];
                    $f_temp[$k3]['num_2'] += $v3['num_2'];
                    $f_temp[$k3]['num_3'] += $v3['num_3'];
                    foreach ($list as $k2222 => $v2222) {
                        if ($v2222['factory_id'] == $k3) {
                            $f_temp[$k3]['factory_name'] = $v2222['factory_name'];
                            break;
                        }
                    }
                }
            }
            foreach ($f_temp as $f_k => $f_v) {
                $res_list[] = $f_v;
            }

            $meta_i--;
            $temp = [
                'id' => $meta_i,
                'sdate' => '',
                'is_auto_import' => 0,
                'factory_id' => 0,
                'factory_name' => "大汇总",
                'num' => 0,
                'num_1' => 0,
                'num_2' => 0,
                'num_3' => 0,
                'ext_data' => [
                    'type' => 'max_meta',
                    'sdate' => $pre_value['sdate'],
                    'is_auto_import' => $pre_value['is_auto_import'],
                ],
            ];
            foreach ($meta_list[$pre_value['sdate']] as $k2 => $v2) {
                foreach ($v2 as $k3 => $v3) {
                    $temp['num'] += $v3['num'];
                    $temp['num_1'] += $v3['num_1'];
                    $temp['num_2'] += $v3['num_2'];
                    $temp['num_3'] += $v3['num_3'];
                }
            }
            $temp = $this->_add_metaAnalysis_bold($temp);
            $res_list[] = $temp;
            $insert_flag['_metaAnalysis_max_list'] = 1;
        }
    }

    private function _where_metaAnalysis($where)
    {
        $where[] = ['bc.factory_id', '>', 0];
        $createDateRange = $this->request->param('create_date_range/s');
        $is_auto_import = $this->request->param('is_auto_import/d', 0);
        $factory_id = $this->request->param('factory_id/d', 0);
        if ($is_auto_import > 0) {
            $where[] = ['bc.is_auto_import', '=', $is_auto_import];
        }
        if ($factory_id > 0) {
            $where[] = ['bc.factory_id', '=', $factory_id];
        }
        if ($createDateRange != '') {
            list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
            $where[] = ['bc.confirm_time', 'between', [$startTime, $endTime + 86399]];
        }
        return $where;
    }

    private function _add_metaAnalysis_bold($temp)
    {
        $temp['factory_name_html'] = "<span class='bold'>{$temp['factory_name']}</span>";
        $temp['num_html'] = "<span class='bold'>{$temp['num']}</span>";
        $temp['num_1_html'] = "<span class='bold'>{$temp['num_1']}</span>";
        $temp['num_2_html'] = "<span class='bold'>{$temp['num_2']}</span>";
        $temp['num_3_html'] = "<span class='bold'>{$temp['num_3']}</span>";
        return $temp;
    }

    public function editUnit()
    {
        $param = $this->request->param();
        Db::startTrans();
        try {
            switch ($param['edit_field']) {
                case 'num_1_num_3_end'://断码率设置
                    switch ($param['ext_data']['type']) {
                        case 'day':
                        case 'min_meta'://设置 日期 来源帐号 ---断码率目标
                            $res = $this->_editUnit_2_factory_id($param['ext_data'], $param['edit_value']);
                            if ($res == false) {
                                Db::rollback();
                                return $this->json(12, '设置失败');
                            }
                            Db::commit();
                            return $this->json(1, '保存成功');
                            break;
                        case 'max_meta_min'://设置 日期 所有来源帐号---断码率目标
                        case 'max_meta':
                            foreach (config('mimo.order_from') as $k => $v) {
                                $res = $this->_editUnit_2_factory_id([
                                    'sdate' => $param['ext_data']['sdate'],
                                    'is_auto_import' => $k,
                                ], $param['edit_value']);
                                if ($res == false) {
                                    Db::rollback();
                                    return $this->json(12, '设置失败');
                                }
                            }
                            Db::commit();
                            return $this->json(1, '保存成功');
                            break;
                    }
                    break;
                case 'stock_code_all_num':
                    $param['edit_value'] = floatval($param['edit_value']);
                    $ids = [];
                    foreach ($param['ids'] as $k => $v) {
                        if ($v > 0) {
                            $ids[] = $v;
                        }
                    }
                    $list = db('break_code bc')
                        ->field("date_format(bc.confirm_date,'%Y-%m-%d') as sdate,is_auto_import")
                        ->where([['bc.id', 'in', $ids]])
                        ->group("date_format(bc.confirm_date,'%Y-%m-%d'),is_auto_import ")->select();
                    foreach ($list as $k => $v) {
                        $res = $this->_editUnit_2_factory_id([
                            'sdate' => $v['sdate'],
                            'is_auto_import' => $v['is_auto_import'],
                        ], $param['edit_value']);
                        if ($res == false) {
                            Db::rollback();
                            return $this->json(12, '设置失败');
                        }
                    }
                    Db::commit();
                    return $this->json(1, '保存成功');
                    break;
            }
            // 回滚事务
            Db::rollback();
            return $this->json(101, '设置失败');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->json(100, '设置失败');
        }
    }

    private function _editUnit_2_factory_id($ext_data, $edit_value)
    {
        $info = db('break_code bc')
            ->where([
                ['bc.factory_id', '=', -2],
                ['bc.is_auto_import', '=', $ext_data['is_auto_import']],
            ])
            ->whereRaw(" date_format(bc.confirm_date,'%Y-%m-%d') ='{$ext_data['sdate']}' ")
            ->find();
        if (isset($info['id'])) {
            $temp = db('break_code')->where("id={$info['id']}")->update([
                'ext' => floatval($edit_value),
            ]);
            if ($temp != 1) {
                return false;
            }
        } else {
            $temp = db('break_code')->insert([
                'sku' => "_2_" . date('YmdHIs') . rand(1000, 9999),
                'type' => 0,
                'is_auto_import' => $ext_data['is_auto_import'],
                'average_daily_sales_num' => 0,
                'factory_id' => -2,
                'factory_child_id' => 0,
                'size' => 0,
                'day' => 0,
                'size_day' => 0,
                'confirm_time' => strtotime($ext_data['sdate'] . ' 00:00:00'),
                'confirm_date' => $ext_data['sdate'] . ' 00:00:00',
                'ext' => floatval($edit_value),
                'admin_id' => ADMIN_ID,
                'update_time' => time(),
                'create_time' => time(),
            ]);
            if ($temp != 1) {
                return false;
            }
        }
        return true;
    }

    //断码率目标设置
    private function _metaAnalysis_num_1_num_3_end($list)
    {
        $data_source = [];
        foreach ($list as $k => $v) {
            $data_source[$v['ext_data']['sdate']][$v['ext_data']['is_auto_import']] = 0;
        }
        if ($data_source == []) {
            return $list;
        }
        $sql_or = "";
        foreach ($data_source as $k => $v) {
            foreach ($v as $k2 => $v2) {
                $sql_or .= " (date_format(bc.confirm_date,'%Y-%m-%d') ='{$k}' and bc.is_auto_import={$k2} ) or";
            }
        }
        $sql_or = substr($sql_or, 0, -2);
        $sql = "SELECT   date_format(bc.confirm_date,'%Y-%m-%d') as sdate ,bc.is_auto_import ,bc.factory_id 
,bc.ext
FROM wx_break_code bc
where
bc.factory_id=-2
and (  {$sql_or} )
;";
        $end_list = db()->query($sql);
        foreach ($list as $k => $v) {
            foreach ($end_list as $k2 => $v2) {
                if ($v['ext_data']['sdate'] == $v2['sdate'] && $v['ext_data']['is_auto_import'] == $v2['is_auto_import']) {
                    $list[$k]['num_1_num_3_end'] = floatval($v2['ext']);
                    break;
                }
            }
        }
        return $list;
    }

    /**
     * 操作成功跳转的快捷方法
     * @access protected
     * @param mixed $msg 提示信息
     * @param string $url 跳转的URL地址
     * @param mixed $data 返回的数据
     * @param integer $wait 跳转等待时间
     * @param array $header 发送的Header信息
     * @return void
     */
    protected function success($msg = '', $url = null, $data = '', $wait = 1, array $header = [])
    {
        if (is_null($url) && isset($_SERVER["HTTP_REFERER"])) {
            $url = $_SERVER["HTTP_REFERER"];
        } elseif ('' !== $url) {
            $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : Container::get('url')->build($url);
        }

        $result = [
            'code' => 1,
            'msg' => $msg,
            'data' => $data,
            'url' => $url,
            'wait' => $wait,
        ];

        $type = $this->getResponseType();
        // 把跳转模板的渲染下沉，这样在 response_send 行为里通过getData()获得的数据是一致性的格式
        if ('html' == strtolower($type)) {
            $type = 'jump';
        }
        return json($result);
    }

    /**
     * 操作错误跳转的快捷方法
     * @access protected
     * @param mixed $msg 提示信息
     * @param string $url 跳转的URL地址
     * @param mixed $data 返回的数据
     * @param integer $wait 跳转等待时间
     * @param array $header 发送的Header信息
     * @return void
     */
    protected function error($msg = '', $url = null, $data = '', $wait = 3, array $header = [])
    {
        $type = $this->getResponseType();
        if (is_null($url)) {
            $url = $this->app['request']->isAjax() ? '' : 'javascript:history.back(-1);';
        } elseif ('' !== $url) {
            $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : $this->app['url']->build($url);
        }

        $result = [
            'code' => 0,
            'msg' => $msg,
            'data' => $data,
            'url' => $url,
            'wait' => $wait,
        ];

        if ('html' == strtolower($type)) {
            $type = 'jump';
        }
        return json($result);
    }

    /**
     * 日均销量--统计报表
     * @author zhuguosen 905502314@qq.com
     * @date 2022/3/20
     */
    public function average_daily_sales_num()
    {
        //主题处理
        $themes = $this->request->param('themes', '');
        $themes = $this->_set_get_themes($themes);
        if ($this->request->isAjax()) {
            //获取参数，并处理
            $param = $this->_statistics_getParam();
            $param['type_name'] = '日均销量';
            //查询数据
            $data = $this->_average_daily_sales_searchData($param);
            //处理数据 以适应图表
            $highcharts_data = $this->_statistics_dealWith($param, $data);
            return json(['code' => 0, 'msg' => '', 'data' => $highcharts_data]);
        }
        $assign = [
            'searchdate' => [
                '', date("Y-m-d", time() - 6 * 24 * 3600), date("Y-m-d"), date("Y-m-d", time() - 30 * 24 * 3600), date("Y-m-d"),
                date("Y-m-01", strtotime('-3 month')), date("Y-m-d"),
                date("Y-m-01", strtotime('-6 month')), date("Y-m-d")
            ],
            'factoryKV' => [0 => '请选择'] + getFactoryKV(true),
            'create_date_range' => date("Y-m-d", time() - 7 * 24 * 3600) . ' ~ ' . date('Y-m-d'),
            'themes' => $this->_get_hightchart_themes(),
            'this_themes' => $themes,
            'this_themes_url' => $themes == 'not_load' ? '' : get_domain() . "/static/js/Highcharts@9.3.2/code/themes/{$themes}",
        ];
        return $this->assign($assign)->fetch();
    }

    private function _average_daily_sales_searchData($param)
    {
        $sql_factory = 'bc.factory_id>0';
        if (FACTORY_IDS != '*') {
            $temp = implode(',', FACTORY_IDS);
            $sql_factory = " bc.factory_id in ({$temp} ) ";
        }
        $result = [];
        switch ($param['unit']) {
            case 'month':
                //日均销量  小辉辉
                $sql = "SELECT   date_format(bc.confirm_date,'%y-%m') as sdate ,bc.factory_id ,f.name as factory_name
,sum(bc.average_daily_sales_num) as num
FROM wx_break_code bc
LEFT JOIN wx_factory f ON (bc.factory_id=f.id)
where  bc.is_auto_import=1  and {$sql_factory}
and bc.confirm_time >= {$param['start_time']} and bc.confirm_time <={$param['end_time']}
group by  sdate,bc.factory_id
order by bc.confirm_time asc
";
                $xiaohuihui_3 = db()->query($sql);
                $xiaohuihui_3 = $this->_date_bu($param, $xiaohuihui_3, 'month_0');
                //日均销量  名贵坊
                $sql = "SELECT   date_format(bc.confirm_date,'%y-%m') as sdate ,bc.factory_id ,f.name as factory_name
,sum(bc.average_daily_sales_num) as num
FROM wx_break_code bc
LEFT JOIN wx_factory f ON (bc.factory_id=f.id)
where  bc.is_auto_import=2  and {$sql_factory}
and bc.confirm_time >= {$param['start_time']} and bc.confirm_time <={$param['end_time']}
group by  sdate,bc.factory_id
order by bc.confirm_time asc
";
                $minguifang_3 = db()->query($sql);
                $minguifang_3 = $this->_date_bu($param, $minguifang_3, 'month_0');
                //日均销量  汇总
                $sql = "SELECT   date_format(bc.confirm_date,'%y-%m') as sdate ,bc.factory_id ,f.name as factory_name
,sum(bc.average_daily_sales_num) as num
FROM wx_break_code bc
LEFT JOIN wx_factory f ON (bc.factory_id=f.id)
where  {$sql_factory}
and bc.confirm_time >= {$param['start_time']} and bc.confirm_time <={$param['end_time']}
group by  sdate,bc.factory_id
order by bc.confirm_time asc
";
                $all_3 = db()->query($sql);
                $all_3 = $this->_date_bu($param, $all_3, 'month_0');
                return [
                    'xiaohuihui_3' => $xiaohuihui_3,
                    'minguifang_3' => $minguifang_3,
                    'all_3' => $all_3,
                ];
                break;
            case 'week':
                //日均销量  小辉辉
                $sql = "SELECT    DATE_FORMAT( bc.confirm_date, '%Y-%u' ) AS week
,DATE_FORMAT(date_sub( bc.confirm_date, INTERVAL dayofweek( bc.confirm_date )- 2 DAY ),'%Y-%m-%d') AS sdate
,date_format(bc.confirm_date,'%y-%u') as sdate2 
,bc.factory_id ,f.name as factory_name
,sum(bc.average_daily_sales_num) as num
FROM wx_break_code bc
LEFT JOIN wx_factory f ON (bc.factory_id=f.id)
where  bc.is_auto_import=1 and {$sql_factory}
and bc.confirm_time >= {$param['start_time']} and bc.confirm_time <={$param['end_time']}
group by  sdate2,bc.factory_id
order by bc.confirm_time asc
";
                $xiaohuihui_3 = db()->query($sql);
                $xiaohuihui_3 = $this->_date_bu($param, $xiaohuihui_3, 'week_0');
                //日均销量  名贵坊
                $sql = "SELECT   DATE_FORMAT( bc.confirm_date, '%Y-%u' ) AS week
,DATE_FORMAT(date_sub( bc.confirm_date, INTERVAL dayofweek( bc.confirm_date )- 2 DAY ),'%Y-%m-%d') AS sdate
,date_format(bc.confirm_date,'%y-%u') as sdate2 
,bc.factory_id ,f.name as factory_name
,sum(bc.average_daily_sales_num) as num
FROM wx_break_code bc
LEFT JOIN wx_factory f ON (bc.factory_id=f.id)
where  bc.is_auto_import=2  and {$sql_factory}
and bc.confirm_time >= {$param['start_time']} and bc.confirm_time <={$param['end_time']}
group by  sdate2,bc.factory_id
order by bc.confirm_time asc
";
                $minguifang_3 = db()->query($sql);
                $minguifang_3 = $this->_date_bu($param, $minguifang_3, 'week_0');
                //日均销量  汇总
                $sql = "SELECT   DATE_FORMAT( bc.confirm_date, '%Y-%u' ) AS week
,DATE_FORMAT(date_sub( bc.confirm_date, INTERVAL dayofweek( bc.confirm_date )- 2 DAY ),'%Y-%m-%d') AS sdate
,date_format(bc.confirm_date,'%y-%u') as sdate2 
,bc.factory_id ,f.name as factory_name
,sum(bc.average_daily_sales_num) as num
FROM wx_break_code bc
LEFT JOIN wx_factory f ON (bc.factory_id=f.id)
where  {$sql_factory}
and bc.confirm_time >= {$param['start_time']} and bc.confirm_time <={$param['end_time']}
group by  sdate2,bc.factory_id
order by bc.confirm_time asc
";
                $all_3 = db()->query($sql);
                $all_3 = $this->_date_bu($param, $all_3, 'week_0');
                return [
                    'xiaohuihui_3' => $xiaohuihui_3,
                    'minguifang_3' => $minguifang_3,
                    'all_3' => $all_3,
                ];
                break;
            case 'day':
                //日均销量  小辉辉
                $sql = "SELECT   date_format(bc.confirm_date,'%y-%m-%d') as sdate ,bc.factory_id ,f.name as factory_name
,sum(bc.average_daily_sales_num) as num
FROM wx_break_code bc
LEFT JOIN wx_factory f ON (bc.factory_id=f.id)
where  bc.is_auto_import=1  and {$sql_factory}
and bc.confirm_time >= {$param['start_time']} and bc.confirm_time <={$param['end_time']}
group by  sdate,bc.factory_id
order by bc.confirm_time asc
";
                $xiaohuihui_3 = db()->query($sql);
                $xiaohuihui_3 = $this->_date_bu($param, $xiaohuihui_3, 'day_0');
                //日均销量  名贵坊
                $sql = "SELECT   date_format(bc.confirm_date,'%y-%m-%d') as sdate ,bc.factory_id ,f.name as factory_name
,sum(bc.average_daily_sales_num) as num
FROM wx_break_code bc
LEFT JOIN wx_factory f ON (bc.factory_id=f.id)
where  bc.is_auto_import=2  and {$sql_factory}
and bc.confirm_time >= {$param['start_time']} and bc.confirm_time <={$param['end_time']}
group by  sdate,bc.factory_id
order by bc.confirm_time asc
";
                $minguifang_3 = db()->query($sql);
                $minguifang_3 = $this->_date_bu($param, $minguifang_3, 'day_0');
                //日均销量   汇总
                $sql = "SELECT   date_format(bc.confirm_date,'%y-%m-%d') as sdate ,bc.factory_id ,f.name as factory_name
,sum(bc.average_daily_sales_num) as num
FROM wx_break_code bc
LEFT JOIN wx_factory f ON (bc.factory_id=f.id)
where  {$sql_factory}
and bc.confirm_time >= {$param['start_time']} and bc.confirm_time <={$param['end_time']}
group by  sdate,bc.factory_id
order by bc.confirm_time asc
";
                $all_3 = db()->query($sql);
                $all_3 = $this->_date_bu($param, $all_3, 'day_0');
                return [
                    'xiaohuihui_3' => $xiaohuihui_3,
                    'minguifang_3' => $minguifang_3,
                    'all_3' => $all_3,
                ];
                break;
        }
        return $result;
    }


    /**
     * 首单多裁追踪
     * @author  huanghuixiang
     * @date 2022/11/3 15:47
     */
    public function cuttingTrack(){

        $factoryKV = getFactoryKV(false);
        $orderSizeService = new OrderSizeService();
        $range= array(
            '1'=>"0%以下", '2'=>"0%-10%",'3'=>"10%-20%", '4'=>"20%-30%", '5'=>"30%以上"
        );
        if ($this->request->isAjax() || $this->request->param('export/d', 0)) {
            $where      = $data = [];
            $sku    = $this->request->param('sku/s');
            $orderStatus    = $this->request->param('order_status/s');
            $factoryId      = $this->request->param('factory_id/d', 0);
            $breakType    = $this->request->param('break_type/s','');
            $clientOrdernum    = $this->request->param('client_ordernum/s');
            $createDateRange    = $this->request->param('create_date_range/s');
            $export     = $this->request->param('export/d', 0);
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 20);
            if ($export) {
                set_time_limit(0);
                ini_set('memory_limit', '1024M');
                $page = 1;
                $limit = 99999;
            }
            //订单加一级
            //  order_level($where,'');
            if (!empty($clientOrdernum)) {
                $where[] = ['o.client_ordernum', '=', $clientOrdernum];
            }
            if (!empty($sku)) {
                $where[] = ['o.sku', '=', $sku];
            }
            if (!empty($factoryId)) {
                $where[] = ['o.factory_id', '=', $factoryId];
            }

            //订单状态
            if ($orderStatus == 99) $where[] = ['status', '=', 99];
            elseif ($orderStatus == 999) $where[] = ['client_status', '=', 99];
            elseif($clientOrdernum == '')   $where[]=['o.status', '<>',99];
            if ($orderStatus != '') {
                switch ($orderStatus){
                    case 1:
                        $where[] = ['o.caigou_status', '=', 0];
                        break;
                    case 2:
                        $where[] = ['o.caigou_status', '=', 1];
                        $where[] = ['caichuang_status', '=', 0];
                        break;
                    case 3:
                        $where[] = ['caichuang_status', '=', 1];
                        $where[] = ['o.chejian_status', '=', 0];
                        break;
                    case 4:
                        $where[] = ['o.chejian_status', '=', 1];
                        $where[] = ['o.tail_status', '=', 0];
                        break;
                    case 5:
                        $where[] = ['o.tail_status', '=', 1];
                        $where[] = ['o.real_shipment_status', '=', 0];
                        break;
                    case 6:
                        $where[] = ['o.real_shipment_status', '=', 1];
                        $where[] = ['o.status', '=', 1];
                        break;
                    case 7:
                        $where[] = ['o.status', '=', 2];
                        break;
                }
            }
            //下单时间
            if ($createDateRange != '') {
                list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
                $where[] = ['o.create_time', 'between', [$startTime, $endTime+86399]];
            }

            if ($breakType != '') {
                $where[] = ['o.break_code_status', '=',$breakType];
                if($breakType !=1){
                    $where[] = ['o.tail_status', '<>', 1];
                }
            }

            $where[] = [
                ['o.type', '=', 'new'],
                ['o.caichuang_status', '=', 1],
                ['o.create_time', '>', 1641005322], //时间从2022.1.1开始
            ];
            //只能看到当前用户所属工厂
            if(FACTORY_IDS !='*' && FACTORY_IDS !='' && empty($factory_id) ) {
                $factoryList=explode(',',FACTORY_IDS);
                $where[] = ['o.factory_id', 'in', $factoryList];
            }

            //列表 starting
            $order = 'o.id desc';
            $field1='o.id,o.tail_status,o.caichuang_over_time,o.client_ordernum,o.sku,status,o.create_time,o.order_price,o.type,o.type_ext,o.quantity,o.caichuang_chuanghao,o.caichuang_user_id,o.caichuang_type,o.caichuang_position,o.`factory_id`';
            $field1 .=',case 
                        when  o.status = 99   then  99 
                        when  o.status = 2  then  5 
                        when  o.caigou_status = 1 and o.caichuang_status = 0 then 2
                        when  o.caichuang_status = 1 and o.chejian_status = 0 then 3
                        when  o.chejian_status = 1 and o.tail_status = 0 then 4
                        when  o.tail_status = 1 and o.real_shipment_status = 0 then 5
                        when  o.real_shipment_status = 1 and o.status = 1 then 5
                        when  o.caigou_status = 0   then  1
                        else  5  end as  local_status';
            $field2='stock_m_type,checkcloth_length,shrink_length,material_dosage,shiji_caigou_count,customer_dosage,shicai_count,caichuang_t_wheat_low_length,
                     caichuang_t_wheat_low,caichuang_t_wheat_height_length,caichuang_t_wheat_height,
                     caichuang_t_wheat_low_number,caichuang_t_wheat_height_number,caichuang_t_wheat_height,
                     caichuang_t_wheat_low,caichuang_wheat_low_length,caichuang_wheat_low,caichuang_wheat_height_length,
                     caichuang_wheat_height,need_checkcloth,need_shrink,billing_caigou_count,
                     caichuang_t_strip,caichuang_t_neadend,caichuang_shiji_dosage as caichuang_shiji_dosage';
            $data['data']=db('order o')->where($where)->field($field1)->page($page)->limit($limit)->order($order)->select();
             //列表 ending

            /*
             * 数据统计- staring
             * 统计的数据从2022.1.1开始
             */
            $field_count='os.order_id,o.order_price,os.client_ordernum,(sum(os.shicai_count)-sum(os.order_count)) as diff,
                          ((sum(os.shicai_count)-sum(os.order_count))/sum(os.order_count)) as per_cent';
             $sql_one=db('order o')->field($field_count)->where($where)
                 ->join('order_size os',' o.id=os.order_id   ','left')
                 ->group('o.id')
                 ->buildsql();
             //以裁数区间分组
             $field_count2='t.*,case 
                             when  t.per_cent<0 then  1 
                             when  t.per_cent>=0  and t.per_cent<0.1 then 2 
                             when  t.per_cent>=0.1  and t.per_cent<0.2 then  3
                             when  t.per_cent>=0.2  and t.per_cent<0.3 then  4
                             else 5 end  per_cent_group ';
             //每个订单的成衣库存
            $field_count2 .=',((SELECT IFNULL(sum(st.available_count),0)   from  wx_sku_stock st  where t.client_ordernum=st.client_ordernum  )*t.order_price  ) as total_available_count';
            $sql_two=DB::table($sql_one.' t')->field($field_count2)->buildSql();
            $field_count3='t2.per_cent_group,count(*) as order_num,sum(total_available_count) as total_monkey';
            //统计列表
            $Statis_list=DB::table($sql_two.' t2')->field($field_count3)->group(' t2.per_cent_group   ')->select();
            //总订单数
            $order_total_num= array_sum(array_column($Statis_list, 'order_num'));
            //总损失金额
            $total_lose= array_sum(array_column($Statis_list, 'total_monkey'));

            foreach ($Statis_list as $key=>$value){
                $Statis_list[$key]['range']=$range[$value['per_cent_group']];
                $Statis_list[$key]['ratio'] =round(($value['order_num']/$order_total_num)*100,2)."%";
            }
            $Statis_data['list']=$Statis_list;
            $Statis_data['total_lose']=round($total_lose,2);
            $Statis_data['order_total_num']=$order_total_num;

            /********** 数据统计 ending  ******/

            $skuService = new SkuService();
            $orderMaterialItemService = new OrderMaterialItemService();
    		$materialStockCuttingService = new MaterialStockCuttingService();
            $orderMaterialService = new OrderMaterialService();
            $local_status =config('mimo.local_status');

            foreach ($data['data'] as $k => $v) {
                $omWhere=[
                    ['order_id','=',$v['id']],
                   // ['caichuang_standard','=',1],
                ];
                $osList=$orderSizeService->getListByOrderId($v['id'],'size_name,shicai_count,order_count,delivery_count');
                $data['data'][$k]['factory_name'] = arrayGet($factoryKV, $v['factory_id'], '');

                //上下架状态
                //断码
                $data['data'][$k]['is_shangjia']='';
                $data['data'][$k]['break_code']='';
                $break_info=db('break_code_new')->field('size_day,launch_time,shelf_off_time')->where([['sku','=', $v['sku']]])->find();
                if($v['tail_status'] !=1){
                 $data['data'][$k]['break_code']=isset($break_info['size_day'])?$break_info['size_day']:'';
                }
                if(isset($break_info['launch_time']) && !empty($break_info['launch_time'])){
                    $data['data'][$k]['is_shangjia'] .="上架时间：".date('Y-m-d',$break_info['launch_time']);
                }
                if( isset($break_info['shelf_off_time']) && !empty($break_info['shelf_off_time']) ){
                    $data['data'][$k]['is_shangjia'] .="下架时间：".date('Y-m-d',$break_info['shelf_off_time']);
                }
                //断码 ending

                $orderlist=[];
                $shicailist=[];
                //实裁数
                $shicailist['list']=$osList;
                $shicailist['shicai_count']= array_sum(array_column($osList, 'shicai_count'));
                $data['data'][$k]['shicai_list'] =$shicailist;
                //订单数
                $orderlist['list']=$osList;
                $orderlist['order_count']= array_sum(array_column($osList, 'order_count'));
                $data['data'][$k]['order_list'] =$orderlist;
                //入仓数
                $data['data'][$k]['delivery_count'] = array_sum(array_column($osList, 'delivery_count'));
                //成衣入库数
                $stock_list=db('sku_stock')->field('size_name,available_count')->where(['client_ordernum'=>$v['client_ordernum']])->select();
                $stocknum= array_sum(array_column($osList, 'available_count'));
                $data['data'][$k]['stock_num'] =$stocknum;
                //损失金额
                $data['data'][$k]['lose_money']=$stocknum*$v['order_price'];
                $data['data'][$k]['status']=$local_status[$v['local_status']];
                $data['data'][$k]['pic'] = $skuService->getPicBySku($v['sku'],true);
                //计划采购量
                $data['data'][$k]['material_dosage']= isset($data['data'][$k]['omInfo']['material_dosage'])?$data['data'][$k]['omInfo']['material_dosage']:0;
                //裁数区间： （实裁数-订单数）/订单数
                $per_cen_info=(($shicailist['shicai_count']- $orderlist['order_count'])/$orderlist['order_count']);
                $data['data'][$k]['shicai_section']=round($per_cen_info*100,2).'%';

                //返单时间
                $data['data'][$k]['chufan_time']='';
                $my_return_time=db('order')->field('create_time')->where(['sku'=>$v['sku'],'type_ext'=>'my_return_first'])->order('id asc')->find();
                if(!empty($my_return_time)){
                    $data['data'][$k]['chufan_time']=date('Y-m-d',$my_return_time['create_time']);
                }
                //读取物料表
                $data['data'][$k]['omInfo'] =db('order_material')->where($omWhere)->field($field2)->find();
                if(empty($data['data'][$k]['omInfo'])){
                    $data['data'][$k]['omInfo']=[];
                }
                //实测米数
                if(isset($data['data'][$k]['omInfo']['shrink_length'])  ||  isset($data['data'][$k]['omInfo']['checkcloth_length']) ){
                    $data['data'][$k]['shrink_length']=  $data['data'][$k]['omInfo']['shrink_length'];
                    $data['data'][$k]['checkcloth_length']=  $data['data'][$k]['omInfo']['checkcloth_length'];
                }
                //备料状态
                $where_me[]=['ml.order_id','=',$v['id']];
                $where_me[]=['m.type','in',['fabric']]; //取面料
                $where_me[]=['st.stock_m_type','=',1]; //取备料
                $beiliao_count=db('material_log ml')->field('m.type,m.material_sku,m.self_sku,st.stock_m_type')
                    ->join('material m','ml.material_id=m.id','left')
                    ->join('stock st','ml.material_id=st.material_id','left')
                    ->where($where_me)
                    ->count();
                $data['data'][$k]['beiliao']="否";
                if(!empty($beiliao_count)){
                     $data['data'][$k]['beiliao']="备料";
                }
                //加工费
                @$order_ext_info=db('order_ext')->field('cost_profit,material_cost_total')->where(['order_id'=>$v['id']])->find();
                if(!empty($order_ext_info)){
                    $data['data'][$k]['cost_profit']= $order_ext_info['cost_profit'];
                    $data['data'][$k]['material_cost_total']= $order_ext_info['material_cost_total'];
                    $data['data'][$k]['bili']= @round(($order_ext_info['cost_profit']/$order_ext_info['material_cost_total']),2);
                }else{
                    $data['data'][$k]['cost_profit']=0;
                    $data['data'][$k]['material_cost_total']=0;
                    $data['data'][$k]['bili']=0;
                }

                /**实裁米数、实测米数
                 *
                 * 实现逻辑是参考：cutting这个文件。
                 */
                $omListOK = $orderMaterialService->getListByOrderIdForCutting($v['id'], ['fabric', 'lining'],'mid,return_length,material_id,client_ordernum,caichuang_strip_dosage,caichuang_wheat_height_length,caichuang_wheat_low_length');
                foreach ($omListOK as $kss => $omInfo) {
                    $omListOK[$kss]['omiListCount'] = $orderMaterialItemService->getListByOrderMaterialId($omInfo['mid'],'caichuang_t_wheat_height,length,caichuang_t_wheat_low,caichuang_t_neadend,caichuang_t_strip');
                    $omListOK[$kss]['mscInfo'] = $materialStockCuttingService->getInfoByMaterialId($v['id'], $omInfo['material_id'],'caichuang_t_wheat_height,length,caichuang_t_neadend,caichuang_t_strip');
                }
                $shicai_meters=0;
                $data['data'][$k]['shicai_meters']=0;
                if(!empty($omListOK)){
                    foreach ($omListOK as $omkkk => $omInfo2){
                             if($omkkk==0){
                                 $heightTotal = array_sum(array_column($omInfo2['omiListCount'], 'caichuang_t_wheat_height'))+arrayGet($omInfo2['mscInfo'], 'caichuang_t_wheat_height', 0);
                                 $lowTotal = array_sum(array_column($omInfo2['omiListCount'], 'caichuang_t_wheat_low'))+arrayGet($omInfo2['mscInfo'], 'caichuang_t_wheat_height', 0);
                                 $neadendTotal = array_sum(array_column($omInfo2['omiListCount'], 'caichuang_t_neadend'))+arrayGet($omInfo2['mscInfo'], 'caichuang_t_neadend', 0);
                                 $stripTotal = array_sum(array_column($omInfo2['omiListCount'], 'caichuang_t_strip'))+arrayGet($omInfo2['mscInfo'], 'caichuang_t_strip', 0);
                                 $shicaiCount=array_sum(array_column($osList, 'shicai_count'));
                                 $allStripDosage=$omInfo2['caichuang_strip_dosage']*$shicaiCount;
                                 $shicai_meters=round(($heightTotal*$omInfo2['caichuang_wheat_height_length']) + ($lowTotal*$omInfo2['caichuang_wheat_low_length']) + $neadendTotal + $stripTotal + $allStripDosage + ($heightTotal+$lowTotal)*0.06, 2);
                                 $data['data'][$k]['shicai_meters'] =$shicai_meters;
                                 $data['data'][$k]['shice_meters']=array_sum(array_column($omInfo2['omiListCount'], 'length'))+arrayGet($omInfo2['mscInfo'], 'length', 0)-$omInfo2['return_length'];
                             }
                    }
                }
                //end
            }

            //导出
            if ($export) {
                $this->_exportXls('裁床报表-' .date('YmdHis'), $data['data']);
            }
            $data['Statis']=$Statis_data;
            $data['count'] = db('order o')->where($where)->count('id');
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }
        $assign = [
            'factoryKV' => [0 => '请选择'] + $factoryKV,
            'rangeList' => [0 => '请选择'] + $range,
        ];
        return $this->assign($assign)->fetch();
        }


}